<template>
  <el-tabs v-model="tabActive" class="demo-tabs" @tab-click="tabClick">
    <el-tab-pane
      v-for="item in tabList" 
      :key="item.id" 
      :label="item.name" 
      :name="item.id"
      :disabled="item.id === 2 && pageStatus === 1"
    >

      <div v-if="item.id === 1">
        <ContentWrap>
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">基础信息</div>
            </div>
            <div class="content_main">
              <el-form 
                ref="formRef" 
                :inline="true" 
                :model="formData.data" 
                :rules="formRules" 
                class="-mb-15px"
                label-width="auto"
              >
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="name">
                      <el-input class="formInp" v-model="formData.data.name" clearable placeholder="请输入项目名称"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="code">
                      <el-input class="formInp" v-model="formData.data.code" clearable placeholder="请输入项目编号"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="关联主合同" prop="mainContractId">
                      <div class="flex-s" style="width: 100%">
                        <div class="coord flex-s formInp mr-12">
                          <span v-if="formData.data.contractName">{{ formData.data.contractName }}</span>
                          <span v-else style="color: rgb(159 155 155);">请选择主合同</span>
                        </div>
                        <el-button type="primary" @click="addRelations(1)">选择合同</el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同编号">
                      <el-input
                        class="formInp" 
                        disabled
                        v-model="formData.data.contractNumber"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同金额（含税）">
                      <el-input
                        class="formInp" 
                        disabled
                        v-model="formData.data.amountWithTax"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目类型" prop="projectType">
                      <el-input class="formInp" v-model="formData.data.projectType" placeholder="请输入项目类型"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属部门" prop="departmentId">
                      <el-tree-select
                        class="formInp"
                        v-model="formData.data.departmentId"
                        :data="deptTree"
                        filterable
                        clearable
                        :props="defaultProps"
                        check-strictly
                        default-expand-all
                        placeholder="请选择所属部门"
                        value-key="deptId"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="负责人" prop="leaderId">
                      <div class="flex-s" style="width: 100%">
                        <div class="coord flex-s formInp mr-12">
                          <span v-if="formData.data.leaderName">{{ formData.data.leaderName }}</span>
                          <span v-else style="color: rgb(159 155 155);">请选择负责人</span>
                        </div>
                        <el-button type="primary" @click="addCompanies(1, '选择负责人')">选择负责人</el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="startTime">
                      <el-date-picker
                        v-model="formData.data.startTime"
                        style="width: 100%;"
                        type="date"
                        placeholder="请选择开始时间"
                        @change="e => formData.data.startTime = formatDateToYMD(e)"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间" prop="endTime">
                      <el-date-picker
                        v-model="formData.data.endTime"
                        style="width: 100%;"
                        type="date"
                        placeholder="请选择结束时间"
                        @change="e => formData.data.endTime = formatDateToYMD(e)"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
      
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">项目经理</div>
            </div>
            <div class="content_main">
              <el-table :data="formData.data.projectManagerList">
                <template v-for="item in personalColumn" :key="item.prop">
                  <el-table-column
                    :width="item.width"
                    :align="item.align ? item.align : 'center'" 
                    :label="item.label"
                    :prop="item.prop"
                  >
                    <template #default="scope">
                      <div v-if="item.prop === 'position'">
                        <span v-if="scope.row.position && scope.row.position.length > 0">{{ scope.row.position.join('/') }}</span>
                        <span v-else>-</span>
                      </div>
                      <div v-else-if="item.prop === 'departmentId'">{{ scope.row.departmentId ? findDeptNameById(deptTree, scope.row.departmentId) : '-' }}</div>
                      <div v-else>{{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}</div>
                    </template>
                  </el-table-column>
                </template>
          
                <el-table-column :width="100" align="center" label="操作">
                  <template #default="scope">
                    <el-button link type="danger" @click="companiesDel(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
          
              </el-table>
              <el-button class="addRow" @click="addCompanies(2, '选择项目经理')" plain>
                <el-icon class="mr-6"><Plus /></el-icon>  添加
              </el-button>
            </div>
          </div>
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">关联子合同</div>
            </div>
            <div class="content_main">
              <el-table :data="formData.data.projectSubcontractList">
                <template v-for="item in relationsColumn" :key="item.prop">
                  <el-table-column
                    :width="item.width"
                    :align="item.align ? item.align : 'center'" 
                    :label="item.label"
                    :prop="item.prop"
                  >
                    <template #default="scope">
                      <div v-if="item.prop === 'number'" @click="goContract(scope.row.id)">
                        <span style="color: #409eff;cursor: pointer;">{{ scope.row.number }}</span>
                      </div>
                      <div v-else-if="item.prop == 'category'">
                        <span v-if="scope.row.category || scope.row.category === 0">{{ categoryList.find(item => item.id === scope.row.category).name }}</span>
                        <span v-else>-</span>
                      </div>
                      <div v-else-if="item.prop == 'type'">
                        <span v-if="scope.row.type || scope.row.type === 0">{{ contractTypeList.find(item => item.value === scope.row.type).label }}</span>
                        <span v-else>-</span>
                      </div>
                      <div v-else-if="item.prop === 'department'">{{ scope.row.department ? findDeptNameById(deptTree, scope.row.department) : '-' }}</div>
                      <div v-else>
                        {{ scope.row[item.prop] || (item.type === 'number' ? '0.00' : '-') }}
                      </div>
                    </template>
                  </el-table-column>
                </template>
          
                <el-table-column :width="100" align="center" label="操作">
                  <template #default="scope">
                    <el-button link type="danger" @click="relationsDel(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
          
              </el-table>
              <el-button class="addRow" @click="addRelations(2)" plain>
                <el-icon class="mr-6"><Plus /></el-icon>  添加
              </el-button>
            </div>
          </div>
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">项目成本</div>
            </div>
            <div class="content_main">
              <el-table :data="projectCosts" :row-class-name="tableRowClassName">
                <el-table-column align="center" label="成本类型" prop="name" />
                <el-table-column align="center" label="成本金额" prop="val">
                  <template #default="scope">
                    <span v-if="scope.row.name === '合计'">{{ scope.row.val }}</span>
                    <el-input-number 
                      v-else
                      style="width: 100%"
                      controls-position="right" 
                      :min="0" 
                      v-model="scope.row.val" 
                      @input="e => modalAmount(e, scope.$index)"
                      placeholder="请输入成本含税金额" 
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="content mb-0">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">附加信息</div>
            </div>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input
                    v-model="formData.data.remark"
                    type="textarea"
                    :autosize="{ minRows: 8}"
                    placeholder="请输入备注信息"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上传附件">
                  <div class="upload_box" style="width: 100%;">
                    <UploadFile
                      v-model="formData.data.attachment"
                      class="upload-demo"
                      :http-request="customRequest"
                      :fileSize="20"
                      :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                      :limit="10"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </ContentWrap>
        <ContentWrap class="flex-c">
          <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm">确定</el-button>
          <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
        </ContentWrap>
      </div>

      <div v-else>
        <EndsMeetForm ref="endsMeetDialogRefsss"/>
      </div>

    </el-tab-pane>
  </el-tabs>
  
  

  <!-- 合作单位弹窗 - 勾选数据 -->
  <personalDialog ref="personalDialogRef" @change="personalChange"/>

  <!-- 关联子合同弹窗 - 勾选数据 -->
  <relationsDialog ref="relationsDialogRef" @change="relationsChange"/>
</template>
<script setup>
  import {ref, reactive, inject, nextTick} from "vue"
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as ProjectApi from '@/api/viewsApi/project'
  import * as ContractApi from '@/api/viewsApi/contract'
  import { Plus } from '@element-plus/icons-vue'
  import { defaultProps, handleTree } from '@/utils/tree'
  import { formRules, personalColumn, relationsColumn } from './jsonAndRules'
  import { formatDateToYMD } from '@/utils/index'
  import { dataConversionUtil } from "@/utils/excel";
  import { ElMessage, ElMessageBox } from 'element-plus'
  import personalDialog from './personalDialog.vue'
  import relationsDialog from './contractDialog.vue'
  import { updateFile } from "@/api/infra/file/index.ts"
  import { formatDate } from '@/utils/formatTime' // 时间戳转日期
  import { UploadFile } from "@/components/UploadFile/index.ts"
  import EndsMeetForm from "./endsMeetForm.vue"
  const router = useRouter()
  const userList = inject('userList')
  let setPageStatus = inject('setPageStatus', () => {});
  const deptTree = inject('deptTree')
  const categoryList = reactive([
    {id: 0, name: '主合同'},
    {id: 1, name: '子合同'},
  ])
  const contractTypeList = ref(getIntDictOptions(DICT_TYPE.CONTRACT_TYPE)) // 合同类型数据
  const message = useMessage() // 消息弹窗
  const formRef = ref(null)
  const goBack = inject('goBack', () => {})
  const personalDialogRef = ref(null)
  const relationsDialogRef = ref(null)
  const endsMeetDialogRefsss = ref(null)
  const findDeptNameById = inject('findDeptNameById', () => {})

  const tabActive = ref(1)
  const tabList = ref([
    {id: 1, name: '项目详情'},
    {id: 2, name: '项目收支'},
  ])
  const tabClick = (tab) => {
    tabActive.value = tab.props.name
    if(tab.props.name === 2){
      nextTick(() => {
        endsMeetDialogRefsss.value[0].init(formData.data.id)
      })
    }
  }

  const formData = reactive({
    data: {
      name: '', // 项目名称
      code: '', // 项目编号
      mainContractId: '', // 关联合同
      contractName: '', // 关联合同名称
      contractNumber: '', // 合同编号 
      amountWithTax: '', // 合同金额（含税）
      projectType: '', // 项目类型
      departmentId: '', // 所属部门
      leaderId: '', // 负责人Id
      leaderName: '', // 负责人
      startTime: '', // 开始时间
      endTime: '', // 结束时间
      projectManagerList: [], // 项目经理
      projectSubcontractList: [], // 关联子合同
      managementCost: '', // 管理成本
      otherCost: '', // 其他成本
    }
  })
  provide('formData', formData)
  let loading = ref(false)
  let pageStatus = ref(1) // 1新增  2编辑
  let copyData = ref([])
  const projectCosts = ref([
    {
      val: null,
      name: '管理成本',
    },
    {
      val: null,
      name: '其他成本',
    },
    {
      val: '0.00',
      name: '合计',
    },
  ])

  /** 初始化 **/
  const init = async (type, id) => {
    pageStatus.value = type
    if (id) {
      await getDetails(id)
    }else{
      await modalAmount()
    }
  }
  /** 查询详情信息 */
  const getDetails = async (id) => {
    loading.value = true
    try {
      const data = await ProjectApi.getProjectDetail(id)
      projectCosts.value = [
        {
          val: data.managementCost ? data.managementCost / 100 : 0,
          name: '管理成本',
        },
        {
          val: data.otherCost ? data.otherCost / 100 : 0,
          name: '其他成本',
        },
        {
          val: '0.00',
          name: '合计',
        },
      ]

      if(data.projectManagerList && data.projectManagerList.length > 0){
        data.projectManagerList = data.projectManagerList.map(item => {
          if(item.employee){
            return {
              id: item.employee.id,
              projectId: item.projectId,
              name: item.employee.name,
              phone: item.employee.phone,
              position: item.employee.position,
              departmentId: item.employee.departmentId,
            }
          }
        })
      }

      if(data.projectSubcontractList && data.projectSubcontractList.length > 0){
        data.projectSubcontractList = data.projectSubcontractList.map(item => {
          if(item.contract){
            return {
              id: item.contract.id,
              projectId: item.projectId,
              name: item.contract.name,
              number: item.contract.number,
              category: item.contract.category,
              type: item.contract.type,
              department: item.contract.department,
              amountWithTax: (item.contract.amountWithTax / 100).toFixed(2),
              amountWithoutTax: (item.contract.amountWithoutTax / 100).toFixed(2),
            }
          }
        })
      }
      data.amountWithTax = data.amountWithTax ? (data.amountWithTax / 100).toFixed(2) : '0.00'
      formData.data = data
      modalAmount()
    } finally {
      loading.value = false
    }
  }

  const contractList = ref([])




  /** 合作单位逻辑处理 - 开始 */
  const addCompanies = (type, titleType) => {
    personalDialogRef.value.init(type, titleType)
  }
  const personalChange = (data, type) => {

    if(type === 1){
      const { id, name } = data
      formData.data.leaderId = id
      formData.data.leaderName = name
    }else{
      if(formData.data.projectManagerList.length > 0) {
        let newData = formData.data.projectManagerList.concat(data)
        // 使用 reduce 去重
        newData = newData.reduce((acc, cur) => {
          if (!acc.some(item => item.id === cur.id)) {
            acc.push(cur)
          }
          return acc
        }, [])
        formData.data.projectManagerList = newData
      }else{
        formData.data.projectManagerList = data
      }
    }

  }
  const companiesDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.projectManagerList.splice(index, 1)
    } catch {}

  } 
  /** 合作单位逻辑处理 - 结束 */


  /** 关联子合同逻辑处理 - 开始 */
  const addRelations = (type) => {
    relationsDialogRef.value.init(type)
  }
  const relationsChange = (data, type) => {
    if(type == 1){
      const { contractName, mainContractId, contractNumber, amountWithTax } = data
      formData.data.contractName = contractName
      formData.data.mainContractId = mainContractId
      formData.data.contractNumber = contractNumber
      formData.data.amountWithTax = amountWithTax
    }else{

      if(formData.data.projectSubcontractList.length > 0) {
        let newData = formData.data.projectSubcontractList.concat(data)
        // 使用 reduce 去重
        newData = newData.reduce((acc, cur) => {
          if (!acc.some(item => item.id === cur.id)) {
            acc.push(cur)
          }
          return acc
        }, [])
        formData.data.projectSubcontractList = newData
      }else{
        formData.data.projectSubcontractList = data
      }

    }

  }
  const relationsDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.projectSubcontractList.splice(index, 1)
    } catch {}
  }

  // 跳转合同详情
  const goContract = (id) => {
    router.push({
      path: '/contract',
      query: {
        id,
      }
    })
  }
  /** 关联子合同逻辑处理 - 结束 */




  /** 项目成本 - 逻辑处理 - 开始 */
  const tableRowClassName = ({ row, rowIndex }) => {
    if (row.name === '合计') {
      return "bg-black"
    }
  }
  // 项目成本 - 合计
  const modalAmount = (e, index) => {
    if(e){
      projectCosts.value[index].val = e
    }
    
    let managementCost = 0
    let otherCost = 0
    projectCosts.value.forEach(item => {
      if(item.name === '管理成本'){
        managementCost += item.val ? item.val : 0
      }
      if(item.name === '其他成本'){
        otherCost += item.val ? item.val : 0
      }
    })
    projectCosts.value[2].val = (managementCost + otherCost).toFixed(2)
    formData.data.managementCost = managementCost
    formData.data.otherCost = otherCost
  }
  /** 项目成本 - 逻辑处理 - 结束 */



  const customRequest = async (options) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      formData.data.attachment.push(res.data)
    }finally {
      
    }
    
  }





  const submitForm = async () => {
    const formEl = formRef.value[0]
    console.log(formEl, 'formEl');
    
    if (!formEl) return

    formEl.validate((valid, fields) => {
      if (valid) {
        let parmsData = JSON.parse(JSON.stringify(formData.data))
        parmsData.projectManagerList = parmsData.projectManagerList.map(item => {
          return {
            managerId: item.id,
          }
        })
    
    
        parmsData.projectSubcontractList = parmsData.projectSubcontractList.map(item => {
          return {
            contractId: item.id,
          }
        })
    
    
    
        if(typeof parmsData.startTime !== 'number'){
          parmsData.startTime = toTimestamp(parmsData.startTime)
        }
    
        if(typeof parmsData.endTime !== 'number'){
          parmsData.endTime = toTimestamp(parmsData.endTime)
        }
    
        parmsData.managementCost = parmsData.managementCost * 100
        parmsData.otherCost = parmsData.otherCost * 100
    
        if (pageStatus.value === 1) {
          ProjectApi.addProject(parmsData).then(res => {
            goBack()
            ElMessage.success('新增成功')
          })
        } else {
          ProjectApi.editProject(parmsData).then(res => {
            goBack()
            ElMessage.success('编辑成功')
          })
        }
      }else{
        for(let key in fields){
          ElMessage.error(fields[key][0].message)
        }
      }
    })
    



  }

  const closeForm = () => {
    // 关闭表单弹窗逻辑
    goBack()
  }
  defineExpose({
    init,
  })

  // 转时间戳
  function toTimestamp(dateStr) {
    console.log(dateStr, '没有传入？？？？');
    
    return new Date(dateStr.replace(/-/g, '/')).getTime();
  }
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    margin-bottom: 24px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
    .content_main {
        width: 100%;
        padding: 0 32px;
        box-sizing: border-box;
    }
}
::v-deep .el-form-item{
  width: 100%;
}
.formInp{
  width: 100%;
}

.addRow{
  margin-top: 12px;
  width: 100%;
}
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  .improtTxt{
    color: #0c84fd;
    cursor: pointer;
    font-size: 12px;
  }

  ::v-deep .bg-black {
      background-color: #F2F2F2;
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      color: #1D1D1D;
  }

.upload_box{
  flex-direction: column;
  .uploader__text{
    margin-top: 6px;
  }
}
::v-deep .el-upload-list{
  overflow-y: scroll;
  height: 120px;
}
.coord{
  height: 32px;
  box-sizing: border-box;
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: not-allowed;
  color: #636660;
}
</style>
